define([
    'jquery',
    'underscore',
    'backbone',
    'module/header/models/HeaderModel',
    'module/header/models/HeaderCollection',
    'module/helper/List',
    'text!module/header/templates/main.html',
    'text!module/header/templates/add.html',
    'text!module/header/templates/edit.html',
    'text!module/header/templates/drop.html',
    'text!module/header/templates/list.html',
], function($, _, Backbone, HeaderModel, HeaderCollection, List, main, add, edit, drop, list) {

    var HeaderController = Backbone.View.extend({
        el: $("#page"),
        initialize: function() {
            this.render();
            this.list_view(1);
        },
        events: {
            "click #list_view": "list_view",
            "click #add_view": "add_view",
            "click #edit_view": "edit_view",
            "click #drop_view": "drop_view",
            "click #add_action": "add_action",
            "click #edit_action": "edit_action",
            "click #drop_action": "drop_action",
            "click #search": "search",
            "click #pag": "pag_action"
        },
        render: function() {
            this.$el.html(main);
            $("#title").html(this.options.title);
        },
        list_view: function(pag) {
            $.get('server/api/header/find_all/' + this.options.type + '/' + pag, function(data) {
                var collection = new HeaderCollection(data.result);
                var listv = new List({collection: collection, count: data.count, pag: pag, list: list});
                listv.render();
            }, "json");
        },
        add_view: function() {
            $("#main-list").html(add);
            $('#date').datepicker({
                onSelect: function(dateText, inst) {
                    $.post('server/api/charge/current', {date: dateText}, function(data) {
                        $("#type_change").val(data.id);
                        $("#type_change_value").val(data.value);
                    }, "json");
                }
            });
            var current_date = new Date();
            $("#date").datepicker('setDate', current_date);
            $.post('server/api/charge/current', {date: current_date.getFullYear() + "/" + current_date.getMonth() + "/" + current_date.getDay()}, function(data) {
                $("#type_change").val(data.id);
                $("#type_change_value").val(data.value);
            }, "json");
            autocomplete(this.options.type);
            //------------------------------------------------------------------
            $.get('server/api/doctype/find', function(data) {
                $.each(data, function(i, item) {
                    var option = document.createElement('option');
                    $(option).val(item.id);
                    $(option).html(item.name);
                    $("#document_id").append(option);
                });
            }, "json");
            $.get('server/api/dociden/find', function(data) {
                $.each(data, function(i, item) {
                    var option = document.createElement('option');
                    $(option).val(item.id);
                    $(option).html(item.name);
                    $("#operator_type").append(option);
                });
            }, "json");
        },
        edit_view: function(event) {
            $("#main-list").html(edit);
            $('#date').datepicker({
                onSelect: function(dateText, inst) {
                    $.post('server/api/charge/current', {date: dateText}, function(data) {
                        $("#type_change").val(data.id);
                        $("#type_change_value").val(data.value);
                    }, "json");
                }
            });
            var current_date = new Date();
            $("#date").datepicker('setDate', current_date);
            $.post('server/api/charge/current', {date: current_date.getFullYear() + "/" + current_date.getMonth() + "/" + current_date.getDay()}, function(data) {
                $("#type_change").val(data.id);
                $("#type_change_value").val(data.value);
            }, "json");
            autocomplete(this.options.type);
            var id = event.target.getAttribute('index');
            var header = new HeaderModel({id: id});
            header.fetch({
                success: function(data) {
                    data = data.toJSON()
                    $("#id").val(data.id);
                    $("#serie").val(data.serie);
                    $("#number").val(data.number);
                    $("#document_id").val(data.document_id);
                    $("#date").val(data.date);
                    $("#operator_id").val(data.operator_id);
                    $("#operator_type").val(data.operator_type);
                    $("#subtotal").val(data.subtotal);
                    $("#tax").val(data.igv);
                    $("#total").val(data.total);
                    $("#type_change").val(data.type_change);

                    $.post('server/api/charge/current', {date: $("#date").val()}, function(data) {
                        $("#type_change").val(data.id);
                        $("#type_change_value").val(data.value);
                    }, "json");
                    $.get('server/api/operator/' + $("#operator_id").val(), {}, function(data) {
                        $("#operator_name").val(data.name);
                        $("#operator_code").val(data.code);
                        $("#operator_address").val(data.address);
                    }, "json");
                }
            });
        },
        drop_view: function(event) {
            $("#main-list").html(drop);
            var id = event.target.getAttribute('index');
            var header = new HeaderModel({id: id});
            header.fetch({
                success: function(data) {
                    data = data.toJSON()
                    $("#id").val(data.id);
                    $("#serie").val(data.serie);
                    $("#number").val(data.number);
                    $("#document_id").val(data.document_id);
                    $("#date").val(data.date);
                    $("#operator_id").val(data.operator_id);
                    $("#operator_type").val(data.operator_type);
                    $("#subtotal").val(data.subtotal);
                    $("#tax").val(data.tax);
                    $("#total").val(data.total);
                    $("#type_change").val(data.type_change);
                    $.post('server/api/charge/current', {date: $("#date").val()}, function(data) {
                        $("#type_change").val(data.id);
                        $("#type_change_value").val(data.value);
                    }, "json");
                    $.get('server/api/operator/' + $("#operator_id").val(), {}, function(data) {
                        $("#operator_name").val(data.name);
                        $("#operator_code").val(data.code);
                        $("#operator_address").val(data.address);
                    }, "json");
                }
            });
        },
        add_action: function() {
            var self = this;

            if (($("#serie").val()).length == 0 || !parseInt($("#serie").val())) {
                alert("Ingrese serie y debe ser numerico");
                return;
            }
            if (($("#number").val()).length == 0 || !parseInt($("#number").val())) {
                alert("Ingrese número y debe ser numerico");
                return;
            }
            var header = new HeaderModel();



            var operationDetails = {
                serie: $("#serie").val(),
                number: $("#number").val(),
                document_id: $("#document_id option:selected").val(),
                date: $("#date").val(),
                operator_id: $("#operator_id").val(),
                operator_type: $("#operator_type option:selected").val(),
                money_type: $("#money_type option:selected").val(),
                type: this.options.type,
                subtotal: $("#subtotal").val(),
                tax: $("#tax").val(),
                total: $("#total").val(),
                type_change: $("#type_change").val(),
                config_tax: $("#config_tax").val(),
                config_current_year: $("#config_current_year").val(),
                config_current_month: $("#config_current_month").val()
            };
            header.save(operationDetails, {
                success: function(data) {
                    self.list_view(1);
                }
            });
        },
        edit_action: function() {
            var self = this;
            var header = new HeaderModel();
            var headerDetails = {
                id: $("#id").val(),
                serie: $("#serie").val(),
                number: $("#number").val(),
                document_id: $("#document_id").val(),
                date: $("#date").val(),
                operator_id: $("#operator_id").val(),
                operator_type: $("#operator_type").val(),
                type: this.options.type,
                subtotal: $("#subtotal").val(),
                tax: $("#tax").val(),
                total: $("#total").val(),
                type_change: $("#type_change").val()
            };

            header.save(headerDetails, {
                success: function(data) {
                    self.list_view(1);
                }
            });
        },
        drop_action: function() {
            var self = this;
            var header = new HeaderModel({
                id: $("#id").val()
            });
            header.destroy({
                success: function(data) {
                    self.list_view(1);
                }
            });
        },
        search: function() {
            var search = $('#txt_search').val();
            $.ajax({
                url: 'server/api/header/search/' + search,
                type: 'GET',
                dataType: "json",
                success: function(data) {
                    var collection = new HeaderCollection(data.result);
                    var list = new List({collection: collection, count: data.count});
                    list.render();
                }
            });
        },
        pag_action: function(event) {
            var pag = event.target.getAttribute('index');
            this.list_view(pag);
        }
    });
    return HeaderController;
});
function autocomplete(type) {
    var url = "";
    if (type == 1) {
        url = "server/api/article/search_pucharse/";
    }
    else if (type == 2) {
        url = "server/api/article/search_sale/";
    }


    $("#operator_name").autocomplete({
        minLength: 2,
        source: function(request, response) {
            $.ajax({
                url: "server/api/operator/search_name/" + type + "/" + $("#operator_name").val(),
                dataType: "json",
                data: {},
                success: function(data) {
                    response($.map(data.result, function(item) {
                        return {
                            label: item.name + ", RUC : " + item.code,
                            value: item.name,
                            id: item.id,
                            ruc: item.code,
                            address: item.address
                        }
                    }));
                }
            });
        },
        select: function(event, ui) {
            $("#operator_id").val(ui.item.id);
            $("#operator_code").val(ui.item.ruc);
            $("#operator_address").val(ui.item.address);
        },
        open: function() {
            $("#operator_id").val("");
        },
        close: function() {
            //$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });
    $("#operator_code").autocomplete({
        minLength: 2,
        source: function(request, response) {
            $.ajax({
                url: "server/api/operator/search_code/" + type + "/" + $("#operator_code").val(),
                dataType: "json",
                data: {},
                success: function(data) {
                    response($.map(data.result, function(item) {
                        return {
                            label: item.name + ", RUC : " + item.code,
                            value: item.code,
                            id: item.id,
                            name: item.name,
                            address: item.address
                        }
                    }));
                }
            });
        },
        select: function(event, ui) {
            $("#operator_id").val(ui.item.id);
            $("#operator_name").val(ui.item.name);
            $("#operator_address").val(ui.item.address);
        },
        open: function() {
            $("#operator_id").val("");
        },
        close: function() {
            //$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });



}